package com.motu.data;

import com.motu.vertx.module.utility.commondata.CommonDataManager;
import com.motu.vertx.module.utility.kafka.KafkaManager;
import com.motu.vertx.module.utility.logsdk.ChargePackage;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.client.WebClient;
import io.vertx.ext.web.client.WebClientOptions;
import io.vertx.kafka.client.producer.KafkaProducer;
import io.vertx.kafka.client.producer.KafkaProducerRecord;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Properties;

/**
 * 魔兔广告数据管理类
 */
public class MotuAdManager {


	private static final Logger logger = LoggerFactory.getLogger(MotuAdManager.class);
	public static KafkaProducer<String, String> ad_producer;
	public static WebClient webClient;
	public static final String KAFKA_TOPIC_AD = "log_colloction_ad";// kafka主题名称

	// 事件名称
	public static final String EVENT_REGISTER = "register";//注册事件
	public static final String EVENT_LOGIN = "login";//登录事件
	public static final String EVENT_CHARGE = "charge";//充值事件


	/**
	 * 初始化魔兔广告kafka配置（需要在进程初始化调用）
	 *
	 * @param vertx
	 * @param appConfig
	 */
	public static void init(Vertx vertx, JsonObject appConfig) {
		webClient = WebClient.create(vertx, new WebClientOptions().setKeepAlive(true));

		//  广告系统 游戏行为事件 kafka地址
		String address = appConfig.getString("ad-collection-kafka-address");
		if (!Tool.isEmpty(address)) {
			Properties ad_config = new Properties();
			ad_config.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, address);
			ad_config.put("key.serializer", StringSerializer.class);
			ad_config.put("value.serializer", StringSerializer.class);
			ad_config.put("acks", "1");
			// 优化kafka生产者配置
			KafkaManager.upgradeProducerConfig(ad_config, appConfig);
			// 创建一个Kafka Producer
			ad_producer = KafkaProducer.create(vertx, ad_config);
			logger.info("motu ad kafka init success address:{}", address);
		}
	}

	/**
	 * 获取公共参数
	 *
	 * @param eventName       事件名称
	 * @param userId      	  用户ID
	 * @param userLoginDevice 用户登录设备信息
	 * @return 上报公共参数
	 */
	public static JsonObject getCommonParams(String eventName, long userId, UserLoginDevice userLoginDevice) {
		if (userLoginDevice == null) {
			logger.error("MotuAdManager send error loginDeviceInfo is null userId:{} eventName:{}", userId, eventName);
			return null;
		}

		// 获取应用包appKey
		ChargePackage chargePackage = CommonDataManager.getChargePackage(ChargePackage.TYPE_COLLCTION_AD, userLoginDevice.getPlatform(), userLoginDevice.getChannel());
		if (chargePackage == null || !chargePackage.hasReyunKey()) {
			return null;
		}
		String appKey = chargePackage.getReyunKey();

		// 获取魔兔广告设备id和类型（不能为空）
		String adDeviceId = userLoginDevice.getMotuAdDeviceId();// 魔兔广告设备id
		String adDeviceType = userLoginDevice.getMotuAdDeviceType();// 魔兔广告设备类型
		if (Tool.isEmpty(adDeviceId)) {
			logger.error("MotuAdManager send error adDeviceId is null userId:{} eventName:{}", userId, eventName);
			return null;
		}
		if (Tool.isEmpty(adDeviceType)) {
			logger.error("MotuAdManager send error adDeviceType is null userId:{} eventName:{}", userId, eventName);
			return null;
		}

		JsonObject commonParams = new JsonObject();
		commonParams.put("app_key", appKey);
		commonParams.put("event_name", eventName);
		commonParams.put("account_id", userLoginDevice.getAccountId());
		commonParams.put("device_id", adDeviceId);// 魔兔广告设备id
		commonParams.put("device_type", adDeviceType);// 魔兔广告设备类型
		commonParams.put("idfa", userLoginDevice.getIdfa());
		commonParams.put("idfv", userLoginDevice.getIdfv());
		commonParams.put("caid", userLoginDevice.getCaid());
		commonParams.put("last_caid", userLoginDevice.getLastCaid());
		commonParams.put("imei", userLoginDevice.getImei());
		commonParams.put("oaid", userLoginDevice.getOaid());
		commonParams.put("android_id", userLoginDevice.getAndroidId());
		commonParams.put("ua", userLoginDevice.getUa());
		commonParams.put("os", Tool.isEmpty(userLoginDevice.getRyos()) ? "other" : userLoginDevice.getRyos().toLowerCase());
		commonParams.put("ip", userLoginDevice.getIp());
		commonParams.put("simulator", userLoginDevice.getSimulator());
		return commonParams;
	}

	/***
	 * 登录事件
	 * @param userId      	  用户ID
	 * @param userLoginDevice 用户登录设备信息
	 */
	public static void sendLoginEvent(long userId, UserLoginDevice userLoginDevice) {
		JsonObject params = getCommonParams(EVENT_LOGIN, userId, userLoginDevice);
		if (params == null) {
			return;
		}
		pushToQueue(params);
	}

	/***
	 * 注册事件
	 * @param userId      	  用户ID
	 * @param userLoginDevice 用户登录设备信息
	 */
	public static void sendRegisterEvent(long userId, UserLoginDevice userLoginDevice) {
		JsonObject params = getCommonParams(EVENT_REGISTER, userId, userLoginDevice);
		if (params == null) {
			return;
		}
		pushToQueue(params);
	}

	/***
	 * 充值事件
	 * @param userId      	  用户ID
	 * @param userLoginDevice 用户登录设备信息
	 * @param orderId 订单id
	 * @param money 付费金额（人民币：元）
	 */
	public static void sendChargeEvent(long userId, UserLoginDevice userLoginDevice, String orderId, double money) {
		JsonObject params = getCommonParams(EVENT_CHARGE, userId, userLoginDevice);
		if (params == null) {
			return;
		}
		params.put("order_id", orderId);
		params.put("pay_amount", (int) (money * 100));// 上报单位：分
		pushToQueue(params);
	}

	/***
	 * 充值事件--新方法(新增字段)
	 * @param userId      	  用户ID
	 * @param userLoginDevice 用户登录设备信息
	 * @param orderId 订单id
	 * @param money 付费金额（人民币：元）
	 * @param totalChargeNum 角色充值的次数
	 * @param countMoneyNum 角色充值当前金额的次数
	 */
	public static void sendChargeEvent(long userId, UserLoginDevice userLoginDevice, String orderId, double money, int totalChargeNum, int countMoneyNum) {
		JsonObject params = getCommonParams(EVENT_CHARGE, userId, userLoginDevice);
		if (params == null) {
			return;
		}
		params.put("order_id", orderId);
		params.put("pay_amount", (int) (money * 100));// 上报单位：分
		params.put("role_pay_num", totalChargeNum);// 角色充值的次数
		params.put("role_pay_now_amount_cnt", countMoneyNum);// 角色充值当前金额的次数（包含当前充值次数，即首次充值328，此值也为1）
		pushToQueue(params);
	}


	/**
	 * 日志发送到消息队列
	 *
	 * @param params 发送参数
	 */
	public static void pushToQueue(JsonObject params) {
		logger.info("MotuAdManager send params:" + params);
		String topicName = KAFKA_TOPIC_AD;
		if (ad_producer == null) {
			logger.error("MotuAdManager pushDBQueue fail producer is null!! topicName:" + topicName);
			return;
		}
		KafkaProducerRecord<String, String> record = KafkaProducerRecord.create(topicName, params.toString());
		ad_producer.send(record, done -> {
			if (done.failed()) {
				logger.error("MotuAdManager pushDBQueue fail params:{} cause:{}", params, Tool.getException(done.cause()));
			} else {
//				RecordMetadata recordMetadata = done.result();
			}
		});
	}

}
